package cn.rongdao.jrkabao.ui.cashadvance;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.FRBaseNeedLocationActivity;
import cn.rongdao.jrkabao.bean.cashadvance.CashPayPrepareBean;
import cn.rongdao.jrkabao.bean.cashadvance.ProtocolBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.model.cashadvance.CashPeyPrepareModel;
import cn.rongdao.jrkabao.model.cashadvance.GetProtocolModel;
import cn.rongdao.jrkabao.ui.cashadvance.event.ProtocolSuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.CashGoPayCreditCardInfoUIComponent;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.CashGoPayUIComponent;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.PaymentDateUIComponent;
import cn.rongdao.jrkabao.ui.webview.WebViewActivity;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.growingio.BuriedUtil;

/**
 * Created by jack on 2017/11/4
 */

public class CashGoPayActivity extends FRBaseNeedLocationActivity {

    private static final String CASH_COUPON_ID = "cash_coupon_id";
    private static final String IS_HAN_YIN = "is_han_yin";
    private static final String IS_JI_FEN = "is_ji_fen";

    public static void start(Context context, boolean isHanYin, boolean isJiFen, String cashCouponId, String institutionId) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_HAN_YIN, isHanYin);
        bundle.putBoolean(IS_JI_FEN, isJiFen);
        bundle.putString(CASH_COUPON_ID, cashCouponId);
        bundle.putString(CashAdvanceActivity.INSTITUTION_ID, institutionId);
        FRStartActivity.start(context, CashGoPayActivity.class, bundle);
    }

    @BindView(R.id.acg_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.acg_ash_gopay)
    CashGoPayUIComponent cashGoPayUIComponent;
    @BindView(R.id.acg_payment_date)
    PaymentDateUIComponent paymentDateUIComponent;
    @BindView(R.id.acg_credit_card_info)
    CashGoPayCreditCardInfoUIComponent cashGoPayCreditCardInfoUIComponent;
    @BindView(R.id.acg_tv_go_cash)
    TextView tvGoCash;
    @BindView(R.id.acg_view_line)
    View viewLine;
    @BindView(R.id.acg_ll_check)
    LinearLayout llCheck;
    @BindView(R.id.acg_check)
    CheckBox checkBox;
    @BindView(R.id.acg_service_protocol)
    TextView tvServiceProtocol;


    private String cashCouponId;
    private boolean isHanYin;

    private String mUrl;
    private String mOrderNum;
    private String institutionId;
    private boolean isSendMsg;
    private boolean isJiFen;

    private String protocolUrl;
    private String protocolName;
    private boolean isShowProtocol;
    private boolean isProtocol;
    private boolean isCheck;

    private boolean isLocation;
    private boolean isCreateOrder;

    @Override
    protected int layoutRes() {
        return R.layout.activity_cash_gopay;
    }

    @Override
    protected void initView() {
        super.initView();
        startLocate();
        BuriedUtil.kamao_yemian_jiazaiwancheng_apply(thisActivity(), 5);
        initTitleBar();
        initData();

        initListener();
    }

    private void initListener() {
        if (!isHanYin) {
            cashGoPayCreditCardInfoUIComponent.setOnNextButtonStyleListener(new CashGoPayCreditCardInfoUIComponent.OnNextButtonStyleListener() {
                @Override
                public void onNextButton(boolean isInput) {
                    tvGoCash.setEnabled(isInput);
                }
            });
            cashGoPayCreditCardInfoUIComponent.setOnSendShortMsgListener(new CashGoPayCreditCardInfoUIComponent.OnSendShortMsgListener() {
                @Override
                public void onSendMsg(boolean sendMsg) {
                    isSendMsg = sendMsg;
                }
            });
        }

        tvServiceProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!FRString.isEmpty(protocolUrl)) {
                    WebViewActivity.start(thisActivity(), protocolUrl);
                }
            }
        });

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCheck = isChecked;
            }
        });
    }

    private void initData() {
        cashCouponId = getIntent().getStringExtra(CASH_COUPON_ID);
        institutionId = getIntent().getStringExtra(CashAdvanceActivity.INSTITUTION_ID);
        isHanYin = getIntent().getBooleanExtra(IS_HAN_YIN, false);
        isJiFen = getIntent().getBooleanExtra(IS_JI_FEN, false);
        tvGoCash.setText(isHanYin ? "去支付" : "确认");
        tvGoCash.setEnabled(isHanYin);

        CashPeyPrepareModel.getInstance()
                .addParams("trans_amount", FRSharedPreferences.getStringDefault(SPConstant.CASH_ADVANCE_MONEY, ""))
                .addParams("institution_id", institutionId)
                .addParams("coupon_id", FRString.valueOf(cashCouponId))
                .addParams("is_jifen", isJiFen ? "1" : "0")
                .execute(new FRBaseObserver<CashPayPrepareBean>(this, "正在加载") {
                    @Override
                    protected void onBaseNext(CashPayPrepareBean data) {
                        viewLine.setVisibility(View.VISIBLE);
                        tvGoCash.setVisibility(View.VISIBLE);
                        if (isHanYin) {
                            paymentDateUIComponent.setContent("预计到账时间", data.getTransfer_time(), data.getTransfer_tip());
                        } else {
                            cashGoPayCreditCardInfoUIComponent.setVisibility(View.VISIBLE);
                            cashGoPayCreditCardInfoUIComponent.setBindId(data.getBind_id(), data.getOrder_no(), isJiFen);
                            cashGoPayCreditCardInfoUIComponent.setPhoneContent(data.getPhone());
                        }
                        mUrl = data.getToPayUrl();
                        mOrderNum = data.getOrder_no();
                        isCreateOrder = true;
                        if (isLocation) {
                            sendLocation(mOrderNum);
                        }
                        getProtocol();
                        cashGoPayUIComponent.setVisibility(View.VISIBLE);
                        cashGoPayUIComponent.setCreditContent(data.getCredit_card_name(), data.getCredit_card_no(), data.getCredit_card_icon());
                        cashGoPayUIComponent.setDepositContent(data.getBank_card_name(), data.getBank_card_no(), data.getBank_card_icon());
                        cashGoPayUIComponent.setMoney(FRString.valueOf(data.getActual_amount()));
                        cashGoPayUIComponent.setCashInfo(FRString.valueOf(data.getRebate_amount()), FRString.valueOf(data.getTrans_fee()), FRString.valueOf(data.getTrans_amount()));
                    }
                });
    }

    private void getProtocol() {
        GetProtocolModel.getInstance().execute(mOrderNum, new FRBaseObserver<ProtocolBean>(this, "加载中，请稍候...") {
            @Override
            protected void onBaseNext(ProtocolBean data) {
                protocolName = data.getService_protocol();
                protocolUrl = data.getUrl();
                isProtocol = CommonUtil.isStatusSuccess(data.getCompact_status());
                isShowProtocol = CommonUtil.isStatusSuccess(data.getService_protocol_switch());
                if (isShowProtocol) {
                    //协议开
                    llCheck.setVisibility(View.VISIBLE);
                    tvServiceProtocol.setText(FRCollection.appendAsString("《", protocolName, "》", ""));
                } else {
                    llCheck.setVisibility(View.GONE);
                }
                if (isProtocol) {
                    //已签约
                    isCheck = true;
                    checkBox.setChecked(true);
                } else {
                    isCheck = false;
                    checkBox.setChecked(false);
                    if (!FRString.isEmpty(protocolUrl) && !isProtocol) {
                        WebViewActivity.start(thisActivity(), protocolUrl);
                    }
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void protocolSuccessEventMessage(ProtocolSuccessEvent protocolSuccessEvent) {
        isProtocol = true;
        getProtocol();
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitle("确认信息");
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @OnClick(R.id.acg_tv_go_cash)
    public void onViewClicked() {
        BuriedUtil.kamao_zhifu_anniu_apply(getActivity(), 3);
        if (isShowProtocol) {
            if (!isProtocol) {
                FRToast.showToastSafe(FRCollection.appendAsString("请先阅读", protocolName, "并签名", ""));
                return;
            }
            if (!isCheck) {
                FRToast.showToastSafe(FRCollection.appendAsString("请先阅读", protocolName, "并同意", ""));
                return;
            }
        }
        if (isHanYin) {
            if (TextUtils.isEmpty(mUrl)) {
                FRToast.showToastSafe("获取跳转链接失败，请重新进入页面后重试");
                return;
            }
            if (!FRString.isEmpty(cashCouponId)) {
                mUrl = FRCollection.appendAsString(mUrl, cashCouponId, "&coupon_id=");
            }
            WebViewActivity.startWithOrderNum(this, mUrl, mOrderNum);
            finish();
        } else {
            if (!isSendMsg) {
                FRToast.showToastSafe("请先获取验证码");
                return;
            }
            if (cashGoPayCreditCardInfoUIComponent.isInputCorrect()) {
                CashAdvanceSuccessActivity.start(thisActivity(), mOrderNum, institutionId, cashGoPayCreditCardInfoUIComponent.getCvn2()
                        , cashGoPayCreditCardInfoUIComponent.getTermOfValidity(), cashGoPayCreditCardInfoUIComponent.getVerifyDataMsg(), isJiFen);
                finish();
            }
        }
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        mLatitude = bdLocation.getLatitude();
        mLongitude = bdLocation.getLongitude();
        isLocation = true;
        if (isCreateOrder) {
            sendLocation(mOrderNum);
        }
        stopLocate();
    }
}